package com.cs307.redcross.client;

import java.io.Serializable;
import java.util.Vector;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class UsersContent extends Content implements Serializable {

	private static final long serialVersionUID = 4468006641815672683L;
	private DatabaseHandlerServiceAsync databaseHandlerService = (DatabaseHandlerServiceAsync) GWT.create(DatabaseHandlerService.class);	

    private final String COL_WIDTH = "150px";
	
	private VerticalPanel mainPanel;
	private FlexTable mainTable;
	private TextBox firstName;
	private TextBox lastName;
	private TextBox email;
	private TextBox phoneNumber;
	private ListBox carrier;
	private PasswordTextBox oldPass;
	private PasswordTextBox newPass;
	private PasswordTextBox retypeNewPass;
	private Button update;
	
	PopupPanel confirmationPopup;
	VerticalPanel confirmationText;
	Button okButton;
	
	private Vector<Volunteer> volunteerVector;
	
	public UsersContent() {		
		mainPanel = new VerticalPanel();
		mainTable = new FlexTable();
		firstName = new TextBox();
		lastName = new TextBox();
		email = new TextBox();
		phoneNumber = new TextBox();
		carrier = new ListBox();
		oldPass = new PasswordTextBox();
		newPass = new PasswordTextBox();
		retypeNewPass = new PasswordTextBox();
		update = new Button("Update Info");
		
		confirmationPopup = new PopupPanel();
		confirmationText = new VerticalPanel();
		okButton = new Button("Ok");	
		
		initWidget(mainPanel);
		
		//Add the main table to the main panel
		mainPanel.add(mainTable);		
		
		mainTable.setStylePrimaryName("mainTable");
		mainTable.getFlexCellFormatter().setColSpan(1,0,1);
		
		//create firstname textbox
		mainTable.setText(1, 0, "First Name");
		mainTable.setWidget(2, 0, firstName);
		mainTable.getFlexCellFormatter().setColSpan(2, 0, 1);
		firstName.setWidth(COL_WIDTH);
		
		//create lastname textbox
		mainTable.setText(3, 0, "Last Name");
		mainTable.setWidget(4, 0, lastName);
		mainTable.getFlexCellFormatter().setColSpan(4,0,1);
		lastName.setWidth(COL_WIDTH);
		
		//create email textbox
		mainTable.setText(5, 0, "Email");
		mainTable.setWidget(6, 0, email);
		mainTable.getFlexCellFormatter().setColSpan(6, 0, 1);
		email.setWidth(COL_WIDTH);
		
		//create cellphone textbox
		mainTable.setText(7, 0, "Cell Phone");
		mainTable.setWidget(8, 0, phoneNumber);
		mainTable.getFlexCellFormatter().setColSpan(8, 0, 1);
		phoneNumber.setMaxLength(10);
		
		//create carrier listbox
		mainTable.setText(9, 0, "Carrier");
		mainTable.setWidget(10, 0, carrier);
		mainTable.getFlexCellFormatter().setColSpan(10, 0, 1);
		carrier.setWidth(COL_WIDTH);
		
		carrier.addItem("att");
		carrier.addItem("Sprint");
		carrier.addItem("Verizon");
		
		//create oldpassword textbox
		mainTable.setText(11, 0, "Old Password");
		mainTable.setWidget(12, 0, oldPass);
		mainTable.getFlexCellFormatter().setColSpan(12, 0, 1);
		oldPass.setWidth(COL_WIDTH);
		
		//create newpassword textbox
		mainTable.setText(13, 0, "New Password");
		mainTable.setWidget(14, 0, newPass);
		mainTable.getFlexCellFormatter().setColSpan(14, 0, 1);
		newPass.setWidth(COL_WIDTH);
		
		//create retype newpassword textbox
		mainTable.setText(15, 0, "Retype New Password");
		mainTable.setWidget(16, 0, retypeNewPass);
		mainTable.getFlexCellFormatter().setColSpan(16, 0, 1);
		retypeNewPass.setWidth(COL_WIDTH);
		
		//create updateInfo button
		mainTable.setWidget(17, 0, update);
		
		// Listen for mouse events on the updateInfo button
		update.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event){
				updateInfo();
			}
		  });
		  
		 // Listen for keyboard events in the input box.
		 update.addKeyPressHandler(new KeyPressHandler() {
		    public void onKeyPress(KeyPressEvent event) {
		      if (event.getCharCode() == KeyCodes.KEY_ENTER) {
		        updateInfo();
		      }
		    }
		  });
		 
		 databaseHandlerService.getAllVolunteers(new AsyncCallback<Vector<Volunteer>>(){
				public void onFailure(Throwable caught) {
					Window.alert("Failed to get volunteers list");
				}

				public void onSuccess(Vector<Volunteer> result) {
					try {
						volunteerVector = result;
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});

		
		// Move cursor focus to the name text box.
		firstName.setFocus(true);	
	}
	
	
	@SuppressWarnings("null")
	private void updateInfo() {
		
		/*confirmationPopup.clear();
		confirmationText.clear();
		
		confirmationText.add(new Label("Successfully Updated Info!"));
		
		confirmationText.add(new Label("User ID:			" + firstName.getValue()));
		confirmationText.add(new Label("First Name:			" + firstName.getValue()));
		confirmationText.add(new Label("Last Name:			" + lastName.getValue()));
		confirmationText.add(new Label("Email:				" + email.getValue()));
		confirmationText.add(new Label("Cell Phone:			" + phoneNumber.getValue()));
		confirmationText.add(new Label("Carrier:			" + carrier.getItemText(carrier.getSelectedIndex())));
		confirmationText.add(new Label("Old Password:		" + oldPass.getValue()));
		confirmationText.add(new Label("New Password:		" + newPass.getValue()));
		confirmationText.add(new Label("Retype New Password	" + retypeNewPass.getValue()));
		
		confirmationText.add(okButton);

		confirmationPopup.add(confirmationText);
		
		
		confirmationPopup.setPopupPosition(100, 100);
		confirmationPopup.setGlassEnabled(true);
		//confirmationPopup.show();
		
		// Close the confirmation dialog when it is clicked
		okButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event){
				firstName.setValue(null);
				confirmationPopup.hide();
			}
		});
		*/
		databaseHandlerService.startDatabaseHandler( new AsyncCallback<Void>() {
			
			public void onFailure(Throwable caught) {
				Window.alert("Startup failed.");
			}

			public void onSuccess(Void result) {
				try {
					Window.alert("Startup Sucedded");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		String fName = firstName.getValue();
		String lName = lastName.getValue();
		String e = email.getValue();
		String car = carrier.getItemText(carrier.getSelectedIndex());
		String cell = phoneNumber.getValue();
		String pass = newPass.getValue();
		Volunteer vol = null;
		if(newPass.getValue().equals(retypeNewPass.getValue())) {
			if (cell == null) {
				vol = new Volunteer(fName, lName, e, car, "", car, e, pass, vol.getFreeTimeEvents());
			} else {
				vol = new Volunteer(fName, lName, e, car, cell, car, e, pass, vol.getFreeTimeEvents());
			}
		} else
			Window.alert("Password not Matching!");
		for(int i=0; i < volunteerVector.size(); i++) {
			if (volunteerVector.get(i).getFirstName() == fName && volunteerVector.get(i).getLastName() == lName) {
				volunteerVector.get(i).setEmail(e);
				volunteerVector.get(i).setCarrier(car);
				volunteerVector.get(i).setCellPhoneNumber(cell);
				if (volunteerVector.get(i).getPassword() == oldPass.getValue()) {
					if (newPass.equals(retypeNewPass)) {
						volunteerVector.get(i).setPassword(pass);
					}
				} else {
					Window.alert("Incorrect Password");
				}
			}
		}
		
		databaseHandlerService.write(vol, new AsyncCallback<Integer>() {
			
			public void onFailure(Throwable caught) {
				Window.alert("Failed Update Info");
			}

			public void onSuccess(Integer result) {
				try {
					confirmationPopup.clear();
					confirmationText.clear();
					
					confirmationText.add(new Label("Successfully Updated Info!"));

					confirmationText.add(new Label("First Name:			" + firstName.getValue()));
					confirmationText.add(new Label("Last Name:			" + lastName.getValue()));
					confirmationText.add(new Label("Email:				" + email.getValue()));
					confirmationText.add(new Label("Cell Phone:			" + phoneNumber.getValue()));
					confirmationText.add(new Label("Carrier:			" + carrier.getItemText(carrier.getSelectedIndex())));
					confirmationText.add(new Label("Old Password:		" + oldPass.getValue()));
					confirmationText.add(new Label("New Password:		" + newPass.getValue()));
					confirmationText.add(new Label("Retype New Password	" + retypeNewPass.getValue()));
					
					confirmationText.add(okButton);

					confirmationPopup.add(confirmationText);
					
					
					confirmationPopup.setPopupPosition(100, 100);
					confirmationPopup.setGlassEnabled(true);
					//confirmationPopup.show();
					
					// Close the confirmation dialog when it is clicked
					okButton.addClickHandler(new ClickHandler(){
						public void onClick(ClickEvent event){
							firstName.setValue(null);
							lastName.setValue(null);
							email.setValue(null);
							phoneNumber.setValue(null);
							carrier.setValue(0, null);
							oldPass.setValue(null);
							newPass.setValue(null);
							retypeNewPass.setValue(null);
							confirmationPopup.hide();
						}
					});
					Window.alert("Success!!!!!");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
}
